# -*- coding: utf-8 -*-

from odoo.http import request

from marshmallow import Schema, fields as orig_fields
from odoo_contrib.marshmallow import fields

from .fields import VideoUrl, Html, VideoUrlPath


class BeenFavouredField(orig_fields.Boolean):
    def _serialize(self, value, attr, obj, **kwargs):
        try:
            wechat_uid = request.wechat_user.id
        except:
            return False
        try:
            obj_id = obj.id
        except:
            obj_id = obj['id']
        favourites = request.env['exhibition.exhibit_favourites'].search_count([
            ('exhibit', '=', obj_id),
            ('wechat_user', '=', wechat_uid)
        ])
        return favourites > 0


class ExhibitSchemaNoRelation(Schema):
    id_ = fields.Integer(attribute='id', data_key='id')
    name = fields.Str()
    desc = Html()
    view_count = fields.Integer(data_key='viewCount')
    images = fields.List(fields.AttachmentUrl)
    spec = fields.Str()
    code = fields.Str()
    # video_url = VideoUrl(attribute='video', data_key='videoUrl',
    #                             model_xmlid='exhibition.exhibit', filename_field='video_filename')
    video_url = VideoUrlPath(attribute='video', data_key='videoUrl', model_xmlid='exhibition.exhibit')


class ExhibitSchema(ExhibitSchemaNoRelation):
    categories = fields.List(fields.Nested('odoo.addons.exhibition.schemas.marshals.category.CategorySchema'))
    been_favoured = BeenFavouredField(default=False, data_key='beenFavoured')  # dummy default @@


class ExhibitRepositorySchema(Schema):
    entries = fields.List(fields.Nested(ExhibitSchema))
    count = fields.Integer()
